package orderCus;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.Customer;
import common.Item;

public class ItemListServlet extends HttpServlet 
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		//ログインチェック
		HttpSession session = req.getSession();
		Customer user = (Customer)session.getAttribute("user");
		if(user == null || user.equals("null")) resp.sendRedirect(req.getContextPath() +"/index.jsp");
		else
		{
			req.setCharacterEncoding("UTF-8");
			String category = req.getParameter("category");
			String itemname = req.getParameter("itemname");
			StringBuffer msg = new StringBuffer();
			List<Item> list = null;
			
			if(category != null)
			{
				list = Item.find_by_category(category);
				req.setAttribute("cg", category);
				if(list == null || list.size() == 0) msg.append("現在取り扱いがありません。");
			}
			else if( itemname.length() > 0)
			{
				list = Item.find_by_name(itemname);
				req.setAttribute("in", itemname);
				if(list == null || list.size() == 0) msg.append("該当する商品がありません。");
			}
			else
			{
				msg.append("検索項目を選択または入力してください。");
			}
			String url = "/customer/top.jsp";
			//エラーがなければ商品情報をセット
			if(msg == null || msg.length() == 0)
			{
				req.setAttribute("itemlist", list);
				url = "/customer/itemList.jsp";
			}
			req.setAttribute("msg", msg.toString());
			RequestDispatcher dispatcher = req.getRequestDispatcher(url);
			dispatcher.forward(req, resp);
		}	
	}
}
